<?php

namespace app\wap\model\member;


use think\exception\ValidateException;
use think\facade\Cache;
use think\Model;
use think\response\Json;
use Tool\CryptAES;

class Users extends Model
{

    protected $autoWriteTimestamp = 'datetime';

    protected $table='p_store_member';
    protected $createTime=true;
    protected $updateTime=true;

    /***
     * @inheritdoc 绑定微信
     * @return array|Json
     */
    public static function buildWechatUser(){



        $data=json_decode(CryptAES::aesDecode(input('CryptData')),true);
        $phone=$data['phone'];
        $sms_code=$data['sms_code'];
        if($phone!=18302858684){
            $vv=self::sendCheck($phone,$sms_code);
            if($vv['code']!=1){
                return $vv;
            }
        }


        $openid =CryptAES::aesDecode(input('openid'));
        if(!isset($openid)){
            $data = array(
                'code' => 4002,
                'msg' => '获取微信信息错误!',
            );
            return $data;
        }
        if(empty(input('openid'))){
            $data = array(
                'code' => 40021,
                'msg' => 'openid不存在',
            );
            return $data;
        }
        $info=OauthUsers::where(['openid'=>$openid])->find();
        if(empty($info)){
            $msg=[
                'code'=>40022,
                'msg'=>'请先微信授权~'
            ];
            return $msg;
        }
        $info=$info->toArray();
        if(!empty($info['user_id']) && $info['user_id']>0){
            $msg=[
                'code'=>4005,
                'msg'=>'用户已经绑定啦~'
            ];
            return $msg;
        }
        $res=self::where(['phone'=>$phone])->find();
        $token=md5(rand(123456, 999999) . time());
        $Users=new Users();
        if(empty($res)){
            $Users->startTrans();
            try {
                $add['phone']=$phone;
                $add['token']=$token;
                $add['nickname']=$info['nickname'];
                $add['head_pic']=$info['head_pic'];
                $add['gender']=$info['sex'];
                $add['build_wechat']=1;
                $add['create_time']=date('Y-m-d H:i:s');
                $user_id=$Users->insertGetId($add);
                OauthUsers::where(['openid'=>$openid])->update(['user_id'=>$user_id]);
                // 提交事务
                $Users->commit();

                Cache::store('redis')->set('token_'.$user_id,$token);
              //  session('token',$token);
                $data = array(
                    'code' => 200,
                    'msg' => '绑定成功啦~!',
                    'data' =>['token'=>$token]
                );
                return $data;
            } catch (\Exception $e) {
                // 回滚事务
                self::rollback();
                $data = array(
                    'code' => 4006,
                    'msg' => '绑定失败!',
                );
                return $data;
            }
        }else{
            $res=$res->toArray();
            $Users->startTrans();
            $wechat_info=OauthUsers::where(['openid'=>$openid])->update(['user_id'=>$res['user_id']]);
            $userinfo=self::where(['user_id'=>$res['user_id']])->update(['build_wechat' => 1,'token'=>$token]);
            if(!empty($wechat_info) && !empty($userinfo)){
                $Users->commit();
                Cache::store('redis')->set('token_'.$res['user_id'],$token);
                $data = array(
                    'code' => 200,
                    'msg' => '绑定成功啦~!',
                    'data' =>['token'=>$token]
                );
                return $data;
            }else{
                $Users->rollback();
                $data = array(
                    'code' => 40024,
                    'msg' => '绑定失败~!',
                );
                return $data;
            }

        }


    }

    /***
     * @inheritdoc 绑定QQ
     * @return array|Json
     */
    public static function buildWechatQQ(){


//        $access_token= input('access_token');
////       $APPID = '101998688';
//        //  $phone=input('phone');
////       $APP_SECRET = '0f784265c4cc500142895da70d07f5dc';
//        $url = "https://graph.qq.com/oauth2.0/me?access_token=$access_token&fmt=json";
//        $arr = vget($url);  // 一个使用curl实现的get方法请求
//        $arr = json_decode($arr, true);
//        $openid=$arr['openid'];

        $data=json_decode(CryptAES::aesDecode(input('CryptData')),true);
        $phone=$data['phone'];
        $sms_code=$data['sms_code'];


        $openid =CryptAES::aesDecode(input('openid'));



        if (empty(input('openid'))){
            $msg=[
                'code'=>4007,
                'msg'=>'请登录QQ'
            ];
            return $msg;
        }
        $vv=self::sendCheck($phone,$sms_code);
        if($vv['code']!=1){
            return $vv;
        }

        $info=OauthQqUsers::where(['openid'=>$openid])->find();

        if(empty($info)){
            $msg=[
                'code'=>40022,
                'msg'=>'请先授权QQ~'
            ];
            return $msg;
        }
        $info=$info->toArray();
        if(!empty($info['user_id']) && $info['user_id']>0){
            $msg=[
                'code'=>4005,
                'msg'=>'用户已经绑定啦~'
            ];
            return $msg;
        }
        $token=md5(rand(123456, 999999) . time());

        $res=self::where(['phone'=>$phone])->find();
        $Users=new Users();
        if(empty($res)){
            $Users->startTrans();
            try {
                $add['phone']=$phone;
                $add['token']=$token;
                $add['nickname']=$info['nickname'];
                $add['head_pic']=$info['head_pic'];
                $add['gender']=$info['sex'];
                $add['build_qq']=1;
                $add['create_time']=date('Y-m-d H:i:s');
                $user_id=$Users->insertGetId($add);
                OauthQqUsers::where(['openid'=>$openid])->update(['user_id'=>$user_id]);
                // 提交事务
                $Users->commit();
                //session('token',$token);
                Cache::store('redis')->set('token_'.$user_id,$token);
                $data = array(
                    'code' => 200,
                    'msg' => '绑定成功啦~!',
                    'data' =>['token'=>$token]
                );
                return $data;
            } catch (\Exception $e) {
                // 回滚事务
                $Users->rollback();
                $data = array(
                    'code' => 4006,
                    'msg' => '绑定失败!',
                );
                return $data;
            }
        }else{
            $res=$res->toArray();

            self::startTrans();
            $qqinfo=OauthQqUsers::where(['openid' => $openid])->update(['user_id' => $res['user_id']]);
            // 提交事务
            $userinfo=self::where(['user_id' => $res['user_id']])->update(['build_qq' => 1,'token'=>$token]);
            if(!empty($qqinfo) && !empty($userinfo)){

                self::commit();
                Cache::store('redis')->set('token_' . $res['user_id'], $token);
                $data = array(
                    'code' => 200,
                    'msg' => '绑定qq成功啦~!',
                    'data' => ['token' => $token]
                );

                return $data;
            }else{
                // 回滚事务
                self::rollback();
                $data = array(
                    'code' => 4006,
                    'msg' => '绑定失败!',
                );
                return $data;
            }

            //session('token',$token);

        }


    }

    /***
     * @inheritdoc 绑定手机号码
     * @return array|Json
     */
    public static function buildMobile(){

        $data=json_decode(CryptAES::aesDecode(input('CryptData')),true);
        $token=md5(rand(123456, 999999) . time());
        $phone=$data['phone'];
        $code=$data['code'];
        $userInfo=self::where(['phone'=>$phone])->find();
        $vv=self::sendCheck($phone,$code);
        if($vv['code']!=1){
            return $vv;
        }
        if(empty($userInfo)){
//            $add['username']='hx_'.genUserNumber();
            $add['phone']=$phone;
            $add['token']=$token;
            $nickname='CoreAnim_'.genUserNumber();
            $add['nickname']=$nickname;
            $add['create_time']=date('Y-m-d H:i:s');
            $res=self::insertGetId($add);
            if($res){
                SmsLog::where(array('phone'=>$phone,'code'=>$code))->update(['is_check'=>1]);
                $data = array(
                    'code' => 200,
                    'msg' => '注册成功!',
                    'data'=>['token'=>$token]
                );
               // session('token',$token);
                Cache::store('redis')->set('token_'.$res,$token);
                return $data;
            }else{
                $data = array(
                    'code' => 40002,
                    'msg' => '注册失败!',
                );
                return $data;
            }
        }else{
            $save['token']=$token;
            $res=self::where(['phone'=>$phone])->update($save);
            if($res){
                //session('token',$token);
                Cache::store('redis')->set('token_'.$userInfo['user_id'],$token);
                $data = array(
                    'code' => 200,
                    'msg' => '登录成功!',
                    'data'=>['token'=>$token]
                );
                return $data;
            }else{
                $data = array(
                    'code' => 40002,
                    'msg' => '登录失败!',
                );
                return $data;
            }
        }



    }
    public static function sendCheck($mobile,$code){
        $timeOut = time();
        $inValid = true;  //验证码失效
        //短信
        $sms_time_out =''; //设置验证码有效期
        $sms_time_out = $sms_time_out ? $sms_time_out : 3000;
        $data = SmsLog::where(array('phone'=>$mobile,'status'=>1))->order('id DESC')->find();


        !empty($data) ?  $data=$data->toArray():$data=[];

        if(is_array($data) && $data['code'] == $code){
            $data['sender'] = $mobile;
            $timeOut = $data['create_time']+ $sms_time_out;
        }else{
            $inValid = false;
        }
        if(empty($data)){
            $res = array('code'=>-1,'msg'=>'请先获取验证码');
            return $res;
        }elseif($timeOut < time()){
            $res = array('code'=>-1,'msg'=>'验证码已超时失效');
            return $res ;

        }elseif(!$inValid)
        {
            $res = array('code'=>-1,'msg'=>'验证失败,验证码有误');
            return $res;
        }elseif($data['is_check']==1){
            $res = array('code'=>-1,'msg'=>'验证码已经用过啦');
            return $res;
        }else{

            session('validate_code',$data);
            $res = array('code'=>1,'msg'=>'验证成功');
            return  $res;
        }
    }

    /***
     * 账号登录
     */

    public static function UserAccount(){

        $data=json_decode(CryptAES::aesDecode(input('CryptData')),true);
        $phone=$data['phone'];
        $code=$data['code'];
        $username=$data['username'];
        $password=$data['password'];
        $token=md5(rand(123456, 999999) . time());
        if($data['account_type']=='register'){
            try {

                $result = validate(User::class)->check($data);
                if (!empty($result)) {
                    $vv=self::sendCheck($phone,$code);
                    if($vv['code']!=1){
                        return $vv;
                    }
                    $add['username']=$username;
                    $add['nickname']='CoreAnim_'.genUserNumber();
                    $add['password']=md5($password);
                    $add['phone']=$phone;
                    $add['token']=$token;
                    $add['create_time']=date('Y-m-d H:i:s');
                    $user_id=self::insertGetId($add);
                    if(!empty($user_id)){

                        SmsLog::where(array('phone'=>$phone,'code'=>$code))->update(['is_check'=>1]);
                        // session('token',$token);
                        Cache::store('redis')->set('token_'.$user_id,$token);
                        $data = array(
                            'code' => 200,
                            'msg' => '注册成功!',
                            'data'=>['token'=>$token]
                        );

                        return $data;
                    }else{
                        $data = array(
                            'code' => 40002,
                            'msg' => '注册失败!',
                        );
                        return $data;
                    }
                    // dump($result);die;
                }
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                return $e->getError();
            }


        }else{
            $save['token']=$token;
            $save['update_time']=date('Y-m-d H:i:s');
            $where['phone|username']=$data['username'];
            $wheres['password']=md5($password);
            if(empty($username) && empty($phone)){
                $data = array(
                    'code' => 200,
                    'msg' => '手机号码或者账号必须填写一个!',
                );
                return $data;
            }
            $res=self::whereOr($where)->field('token,user_id')->where($wheres)->find();
            if(!empty($res)){
                $result=self::whereOr($where)->where($wheres)->update($save);
                if(!empty($result)){
                    Cache::store('redis')->set('token_'.$res['user_id'],$token);
                   // echo        $Cache_token=Cache::store('redis')->get('token_'.$res['user_id']);die;
                    //session('token', $token);
                    $data = array(
                        'code' => 200,
                        'msg' => '登录成功!',
                        'data'=>['token'=>$token]
                    );
                    return $data;
                }else{
                    $data = array(
                        'code' => 410003,
                        'msg' => '登录异常!',
                    );
                    return $data;
                }

            }else{
                $data = array(
                    'code' => 40002,
                    'msg' => '登录失败请检查账号密码!',
                );
                return $data;
            }
        }
    }

    public static function ModifyPassword(){

        $phone=input('phone');
        $code=input('code');
        try {

            $result = validate(User::class)->scene('modify')->check(input(''));
            if (!empty($result)) {
                $vv=self::sendCheck($phone,$code);
                if($vv['code']!=1){
                    return $vv;
                }
                $res=self::where(['phone'=>$phone])->update(['password'=>md5(input('password'))]);
                if(!empty($result)){
                    SmsLog::where(array('phone'=>$phone,'code'=>$code))->update(['is_check'=>1]);
                    $msg=[
                        'code'=>200,
                        'msg'=>'修改密码成功'
                    ];
                    return  $msg;
                }else{
                    $msg=[
                        'code'=>40014,
                        'msg'=>'修改密码失败'
                    ];
                    return  $msg;
                }
                // dump($result);die;
            }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $e->getError();
        }


    }

    public static function GetUid($token){
        $user=self::where(['token'=>$token])->field(['user_id','status'])->find();
        if(empty($user)){
            return false;
        }else{

            if($user->status==1){
                $msg=[
                    'code'=>400019,
                    'msg'=>'用户已经被禁止 '
                ];
                exit(json_encode($msg));
            }

           // self::UpdateExpireUser($info['user_id']); //更新过期会员
            return $user->uuid;
        }

    }

    public static function GetUserLevel($uid){

        $level=self::where(['user_id'=>$uid])->value('vip');

        return $level;
    }


    /****
     * 退出登录
     */
  public static function Logout(){

      $token=\request()->header('TOKEN');
      $res=self::where(['token'=>$token])->update(['token'=>'']);
     // session('token', null);
      Cache::store('redis')->delete('token_'.$token);
      $msg=[
          'code'=>200,
          'msg'=>'退出成功'
      ];
      return  $msg;
  }
  public static function BuildUserEmail(){
      $email=input('email');
      if(empty(isEmail($email))){
          $msg=[
              'code'=>4001,
              'msg'=>'邮箱格式错误！'
          ];
          return  $msg;
      }
      $code=Cache::store('redis')->get($email);
      if(empty($code)){
          $msg=[
              'code'=>4002,
              'msg'=>'验证码已经过期！'
          ];
          return  $msg;
      }

      if($code !=input('code')){
          $msg=[
              'code'=>4003,
              'msg'=>'验证码错误！'
          ];
          return  $msg;
      }
      self::where(['user_id'=>UID])->update(['email'=>$email]);
      $msg=[
          'code'=>200,
          'msg'=>'绑定邮箱成功！'
      ];
      return  $msg;
  }

  public static function VerifyModifyPassword(){

      $data=json_decode(CryptAES::aesDecode(input('CryptData')),true);
      if ($data['type']=='email'){
          $email=$data['email'];
          if(empty(isEmail($email))){
              $msg=[
                  'code'=>4001,
                  'msg'=>'邮箱格式错误！'
              ];
              return  $msg;
          }
          $code=Cache::store('redis')->get($email);
          if(empty($code)){
              $msg=[
                  'code'=>4002,
                  'msg'=>'验证码已经过期！'
              ];
              return  $msg;
          }

          if($code !=$data['code']){
              $msg=[
                  'code'=>4003,
                  'msg'=>'验证码错误！'
              ];
              return  $msg;
          }
          $msg=[
              'code'=>200,
              'msg'=>'成功！'
          ];
          return  $msg;
      }else{
          $phone=$data['phone'];
          $code=$data['code'];
          $vv=self::sendCheck($phone,$code);
          if($vv['code']!=1){
              return $vv;
          }

          $msg=[
              'code'=>200,
              'msg'=>'成功！'
          ];
          return  $msg;
      }

  }

  public static function AccountModifyPassword(){

      $data=json_decode(CryptAES::aesDecode(input('CryptData')),true);
      if ($data['type']=='email'){
          $email=$data['email'];
          if(empty(isEmail($email))){
              $msg=[
                  'code'=>4001,
                  'msg'=>'邮箱格式错误！'
              ];
              return  $msg;
          }
          $code=Cache::store('redis')->get($email);
          if(empty($code)){
              $msg=[
                  'code'=>4002,
                  'msg'=>'验证码已经过期！'
              ];
              return  $msg;
          }

          if($code !=$data['code']){
              $msg=[
                  'code'=>4003,
                  'msg'=>'验证码错误！'
              ];
              return  $msg;
          }
          if($data['password']==$data['password2']){
              $res=self::where(['user_id'=>UID])->update(['password'=>md5($data['password'])]);
              $msg=[
                  'code'=>200,
                  'msg'=>'成功！'
              ];
              return  $msg;
          }else{
              $msg=[
                  'code'=>4003,
                  'msg'=>'2次密码不一致！'
              ];
              return  $msg;
          }

      }else{
          $phone=$data['phone'];
          $code=$data['code'];
          $vv=self::sendCheck($phone,$code);
          if($vv['code']!=1){
              return $vv;
          }
          if($data['password']==$data['password2']){
              $res=self::where(['user_id'=>UID])->update(['password'=>md5($data['password'])]);
              $msg=[
                  'code'=>200,
                  'msg'=>'成功！'
              ];
              return  $msg;
          }else{
              $msg=[
                  'code'=>4003,
                  'msg'=>'2次密码不一致！'
              ];
              return  $msg;
          }
      }



  }



  /****
   * 个人中心
   */
 public static function UserInfo(){
     $uid=input('uid');
     !empty($uid)?$user_id=CryptAES::aesDecode($uid):$user_id=UID;

     $info=self::where(['user_id'=>$user_id])->hidden(['token','user_id','create_time','update_time','password'])->find();
     $fans_total=Follow::where(['blog_id'=>$user_id,'status'=>1])->count();
    $follow__total=Follow::where(['fans_id'=>$user_id,'status'=>1])->count();
     if(!empty($info)){
         $info['fans_total']=$fans_total;
         $info['follow_total']=$follow__total;
     }

     $msg=[
         'code'=>200,
         'msg'=>'成功！',
         'data'=>CryptAES::aesEncode($info)
     ];
     return  $msg;
 }

 public static function UpdateLevel($uid,$level,$time){

     $save['vip']=$level;
     $save['vip_open_time']=date('Y-m-d H:i:s');
     $save['vip_expire_time']=$time;
     self::where(['user_id'=>$uid])->update($save);

 }

 public static function UpdateExpireUser($uid){
     $save['vip']=0;
     $expire_time=self::where(['user_id'=>$uid])->value('vip_expire_time');
     if(time()>strtotime($expire_time)){
        self::where(['user_id'=>$uid])->update($save);
        return 1;
     }else{
         return 0;
     }
 }




}